import { defineStore } from 'pinia';
import { Session } from '@/utils/storage';
import { ILoginDTO, ISysUser, getUserInfo, login as loginApi, refreshTokenApi } from '@/api/login';
import { useMessage } from '@/hooks/message';

interface IUserInfos {
	user: ISysUser;
	authBtnList: string[];
	photo: string;
	roles: string[];
	time: number;
	userName: string;
}

export const useUserInfoStore = defineStore('userInfo', () => {
	const userInfos = ref<IUserInfos>({} as IUserInfos);

	async function login(data: ILoginDTO) {
		data.grant_type = 'password';
		data.scope = 'server';

		return new Promise((resolve, reject) => {
			loginApi(data)
				.then((res) => {
					// 存储token 信息
					Session.set('token', res.access_token);
					Session.set('refresh_token', res.refresh_token);
					resolve(res);
				})
				.catch((err) => {
					useMessage().error(err?.msg || '系统异常请联系管理员');
					reject(err);
				});
		});
	}

	async function refreshToken() {
		return new Promise((resolve, reject) => {
			const refreshToken = Session.get('refresh_token');
			refreshTokenApi(refreshToken)
				.then((res) => {
					// 存储token 信息
					Session.set('token', res.access_token);
					Session.set('refresh_token', res.refresh_token);
					resolve(res);
				})
				.catch((err) => {
					useMessage().error(err.msg);
					reject(err);
				});
		});
	}

	async function setUserInfos() {
		await getUserInfo().then((res) => {
			userInfos.value = {
				user: res.data.sysUser,
				time: new Date().getTime(),
				roles: res.data.roles,
				authBtnList: res.data.permissions,
				photo: res.data.sysUser.avatar,
				userName: res.data.sysUser.username,
			};
		});
	}

	return { userInfos, login, refreshToken, setUserInfos };
});
